﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Collections;
using System.Drawing;

public partial class Administrar : System.Web.UI.Page
{
    SqlConnection CNx = new SqlConnection();
    SqlConnection CNx2 = new SqlConnection();
    Utilitarios Util = new Utilitarios();

    protected void Page_Load(object sender, EventArgs e)
    {
        CNx.ConnectionString = Utilitarios.Conexion2;
        CNx2.ConnectionString = Utilitarios.Conexion;

        if (Session["IDUsuario"] == null)
        {
            Response.Redirect("Default.aspx");
        };
 
        if (!IsPostBack)
        {
            cargardatos();
            CargarUsuarios();
            llenararbol();
        }
        //if (Page.Request.Params["__EVENTTARGET"] == "GrabarMater(1)") GrabarMater(1);
        //if (Page.Request.Params["__EVENTTARGET"] == "GrabarMater(2)") GrabarMater(2);
        //if (Page.Request.Params["__EVENTTARGET"] == "GrabarMater(3)") GrabarMater(3);
    }

    private void GrabarMater(int op)
    {
        string msg = "";
        string qry = "";
        if (op == 1)
        {
            string v = hid1.Value;
            string mat = cmbMateria.SelectedValue;
            string tabla;
            
            if (v == "SM") tabla = "LEG_SMATERIA (IDM,Descripcion) values ("+mat+",'"+hid2.Value +"')";
            else if (v == "ES") tabla = "LEG_ESTADO (IDMat,Descripcion) values ("+mat+",'"+hid2.Value +"')";
            else tabla = "LEG_SALA (IDM,NombreL) values (" + mat + ",'" + hid2.Value + "')"; ;
            msg = "Insert into " + tabla;
        }
             
        else if (op==2)
        {
            string v = hid1.Value;
            string tabla;
            string id = v.Substring(v.Length - 3, 3);
            string tp = v.Substring(v.Length - 5, 2);
            qry = "Select count(*) from LEG_Expedientes where ";
            if (tp == "SM")
            {
                tabla = "LEG_SMATERIA where IDSM=";
                qry = qry + " IDSMat =";
            }
            else if (tp == "ES")
            {
                tabla = "LEG_ESTADO where IDES=";
                qry = qry + " IDEstado =";
            }
            else
            {
                tabla = "LEG_SALA where IDL=";
                qry = qry + " IDLoc =";
            }
            msg = "Delete from "+tabla+ id;
            qry = qry + id;
        }
        else{
            string v = hid1.Value;
            string vv = hid2.Value;
            string tabla;
            string id = v.Substring(v.Length - 3, 3);
            string tp = v.Substring(v.Length - 5, 2);
            if (tp == "SM") tabla = "LEG_SMATERIA set Descripcion='"+vv+"' where IDSM=";
            else if (tp == "ES") tabla = "LEG_ESTADO Set Descripcion='"+vv+"' where IDE=";
            else tabla = "LEG_SALA SET NombreL ='"+vv+"' where IDL=";
            msg = "Update "+tabla+id;
        }
        
        CNx.Open();
        if (qry != "")
        {
            SqlCommand te = new SqlCommand(qry, CNx);
            int res = (int)te.ExecuteScalar();
            if (res > 0)
            {
                string datos = "No puede eliminar este registro porque esa siendo utilizado!!";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "mensaje('"+datos+"');", true);
                return;
            }
        }
        SqlCommand tb = new SqlCommand(msg, CNx);
        tb.ExecuteNonQuery();
        CNx.Close();
        llenararbol();
        tvMain.ExpandAll();
        //UpdatePanel1.Update();
    }

    private void GrabarTp(int op)
    {
        string msg = "";
        string qry = "";
        if (op == 1)
        {
            qry = "Insert into LEG_TipoProceso (Descripcion) values ('" +hid2.Value+ "')";
        }
        else if (op == 2)
        {
            msg = "Select count(*) from LEG_Expedientes where IDTIP="+hid1.Value;
            qry = "Delete from LEG_TipoProceso where IDTP=" + hid1.Value;

        }
        else
        {
            qry = "Update LEG_TipoProceso set Descripcion = '" + hid2.Value + "' where IDTP=" + hid1.Value;
        }

        CNx.Open();
        if (msg != "")
        {
            SqlCommand te = new SqlCommand(msg, CNx);
            int res = (int)te.ExecuteScalar();
            if (res > 0)
            {
                string datos = "No puede eliminar este registro porque esa siendo utilizado!!";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "mensaje('" + datos + "');", true);
                return;
            }
        }
        SqlCommand tb = new SqlCommand(qry, CNx);
        tb.ExecuteNonQuery();
        CNx.Close();
        cargartp();
    }

    private void cargardatos()
    {
        CNx.Open();
        string msg = "Select * from LEG_TipoProceso";
        SqlCommand tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        ArrayList L1 = new ArrayList();
 
        while (Dr.Read())
        {
            L1.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbTP.DataSource = L1;
        cmbTP.DataTextField = "Nombre";
        cmbTP.DataValueField = "Tag";
        cmbTP.DataBind();
        //Dr.Close();

        msg = "Select * from LEG_VMateria";
        ArrayList L2 = new ArrayList();
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            L2.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbMateria.DataSource = L2;
        cmbMateria.DataTextField = "Nombre";
        cmbMateria.DataValueField = "Tag";
        cmbMateria.DataBind();
        //Dr.Close();

        msg = "Select * from LEG_Ubicacion";
        ArrayList L3 = new ArrayList();
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            L3.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        CNx.Close();
        cmbUbicacion.DataSource = L3;
        cmbUbicacion.DataTextField = "Nombre";
        cmbUbicacion.DataValueField = "Tag";
        cmbUbicacion.DataBind();
        //Dr.Close();

    }

    private void cargartp()
    {
        CNx.Open();
        string msg = "Select * from LEG_TipoProceso";
        SqlCommand tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        ArrayList L1 = new ArrayList();

        while (Dr.Read())
        {
            L1.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbTP.DataSource = L1;
        cmbTP.DataTextField = "Nombre";
        cmbTP.DataValueField = "Tag";
        cmbTP.DataBind();
        Dr.Close();
        CNx.Close();
    }

    private void cargarubi()
    {
        CNx.Open();
        string msg = "Select * from LEG_Ubicacion";
        SqlCommand tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        ArrayList L6 = new ArrayList();

        while (Dr.Read())
        {
            L6.Add(new listas(Dr[0].ToString(), Dr[1].ToString()));
        }
        Dr.Close();
        cmbUbicacion.DataSource = L6;
        cmbUbicacion.DataTextField = "Nombre";
        cmbUbicacion.DataValueField = "Tag";
        cmbUbicacion.DataBind();
        //Dr.Close();
        CNx.Close();
    }

    private void CargarUsuarios()
    {
        CNx2.Open();
        string msg = "Select * from SIS_VUAPP where APP_ID=7 order by Usuario";
        DataTable dt = new DataTable();
        SqlDataAdapter Da = new SqlDataAdapter(msg, CNx2);
        Da.Fill(dt);
        gvUsuarios.DataSource = dt;
        gvUsuarios.DataBind();
        CNx2.Close();
    }

    private void llenararbol()
    {
        string tp = cmbMateria.SelectedValue.ToString();
        string msg = "select nsala from leg_vmateria where idm =" + tp;

        CNx.Open();
        SqlCommand tb = new SqlCommand(msg, CNx);
        string nsala = tb.ExecuteScalar().ToString();
        tvMain.Nodes.Clear();

        TreeNode NodoSM = new TreeNode("Motivos", "SM");
        TreeNode NodoSA = new TreeNode(nsala, "NS");
        TreeNode NodoES = new TreeNode("Estados", "ES");

        msg = "Select * from LEG_SMateria where IDM=" + tp;
        tb = new SqlCommand(msg, CNx);
        SqlDataReader Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            string codigo = "SM" + Util.Ceros((int)Dr[0], 3);
            TreeNode Nodo3 = new TreeNode(Dr[2].ToString(), codigo);
            NodoSM.ChildNodes.Add(Nodo3);
        }
        Dr.Close();

        msg = "Select * from LEG_Sala where IDM=" + tp;
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            string codigo = "SA" + Util.Ceros((int)Dr[0], 3);
            TreeNode Nodo3 = new TreeNode(Dr[2].ToString(), codigo);
            NodoSA.ChildNodes.Add(Nodo3);
        }
        Dr.Close();

        msg = "Select * from LEG_Estado where IDMat=" + tp;
        tb = new SqlCommand(msg, CNx);
        Dr = tb.ExecuteReader();
        while (Dr.Read())
        {
            string codigo = "ES" + Util.Ceros((int)Dr[0], 3);
            TreeNode Nodo3 = new TreeNode(Dr[2].ToString(), codigo);
            NodoES.ChildNodes.Add(Nodo3);
        }
        Dr.Close();

        tvMain.Nodes.Add(NodoSM);
        tvMain.Nodes.Add(NodoSA);
        tvMain.Nodes.Add(NodoES);


        CNx.Close();
    }

    protected void tvMain_SelectedNodeChanged(object sender, EventArgs e)
    {
        string Dato = tvMain.SelectedNode.Value.ToString();
        string r = Dato;
     
    
    }
    protected void cmbMateria_SelectedIndexChanged(object sender, EventArgs e)
    {
        llenararbol();
    }
    protected void btnUP1_Click(object sender, EventArgs e)
    {
        int op = int.Parse(hid3.Value);
        GrabarMater(op);
    }
    protected void btnUP2_Click(object sender, EventArgs e)
    {
        int op = int.Parse(hid3.Value);
        GrabarTp(op);
    }

    protected void gvUsuarios_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView rowView = (DataRowView)e.Row.DataItem;
            string IDU = rowView["IDU"].ToString();
            int nivel = (int)rowView["SEG_1"];
            //DateTime F2 = (DateTime)rowView["FechaFin"];
            ImageButton btn1 = (ImageButton)e.Row.FindControl("btnEdit");
            System.Web.UI.WebControls.Image Img1 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img1");
            System.Web.UI.WebControls.Image Img2 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img2");
            System.Web.UI.WebControls.Image Img3 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img3");
            System.Web.UI.WebControls.Image Img4 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img4");
            System.Web.UI.WebControls.Image Img5 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img5");
            System.Web.UI.WebControls.Image Img6 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img6");
            System.Web.UI.WebControls.Image Img7 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img7");
            System.Web.UI.WebControls.Image Img8 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img8");
            System.Web.UI.WebControls.Image Img9 = (System.Web.UI.WebControls.Image)e.Row.FindControl("img9");
            btn1.Attributes.Add("OnClick", "return verUser(" + IDU+");");
            bool[] rr = new bool[10];
            rr = Util.leve(nivel);
            if (rr[1]) Img1.ImageUrl ="imagenes/check.png";
            if (rr[2]) Img2.ImageUrl = "imagenes/check.png";
            if (rr[3]) Img3.ImageUrl = "imagenes/check.png";
            if (rr[4]) Img4.ImageUrl = "imagenes/check.png";
            if (rr[5]) Img5.ImageUrl = "imagenes/check.png";
            if (rr[6]) Img6.ImageUrl = "imagenes/check.png";
            if (rr[7]) Img7.ImageUrl = "imagenes/check.png";
            if (rr[8]) Img8.ImageUrl = "imagenes/check.png";
            if (rr[9]) Img9.ImageUrl = "imagenes/check.png"; 
        }
    }
    protected void btnVUsers_Click(object sender, EventArgs e)
    {
        int valor = 0;
        int recep = 0;
        if (chk1.Checked) valor = valor + 1;
        if (chk2.Checked) valor = valor + 2;
        if (chk3.Checked) valor = valor + 4;
        if (chk4.Checked) valor = valor + 8;
        if (chk5.Checked) valor = valor + 16;
        if (chk6.Checked) valor = valor + 32;
        if (chk7.Checked) { valor = valor + 64; recep = 1; }
        if (chk8.Checked) valor = valor + 128;
        if (chk9.Checked) valor = valor + 256;
        CNx2.Open();
        string msg = "Update SIS_USERAPP Set SEG_1 = "+valor.ToString()+",SEG_2="+recep.ToString()+" where USR_ID = " + hid10.Value;
        SqlCommand tb = new SqlCommand(msg, CNx2);
        tb.ExecuteNonQuery();
        CNx2.Close();
        CargarUsuarios();
    }

    protected void btnUpUsr_Click(object sender, EventArgs e)
    {
        CNx2.Open();
        string msg = "Select * from SIS_VUAPP where APP_ID = 7 and IDU ="+hid10.Value;
        SqlCommand tb = new SqlCommand(msg, CNx2);
        SqlDataReader Dr = tb.ExecuteReader();
        Dr.Read();
        lblUsuario.Text = Dr["Usuario"].ToString();
        lblNUsuario.Text = Dr["Nombres"].ToString();
        int lev = (int)Dr["SEG_1"];
        Dr.Close();
       
        bool[] level = new bool[10];
        bool bucle = true;
        while (bucle)
        {
            if (lev >= 256) { level[9] = true; chk9.Checked = true; lev = lev - 256; } else chk9.Checked = false;
            if (lev >= 128) { level[8] = true; chk8.Checked = true; lev = lev - 128; } else chk8.Checked = false;
            if (lev >= 64) { level[7] = true; chk7.Checked = true; lev = lev - 64; } else chk7.Checked = false;
            if (lev >= 32) { level[6] = true; chk6.Checked = true; lev = lev - 32; } else chk6.Checked = false;
            if (lev >= 16) { level[5] = true; chk5.Checked = true; lev = lev - 16; } else chk5.Checked = false;
            if (lev >= 8) { level[4] = true; chk4.Checked = true; lev = lev - 8; } else chk4.Checked = false;
            if (lev >= 4) { level[3] = true; chk3.Checked = true; lev = lev - 4; } else chk3.Checked = false;
            if (lev >= 2) { level[2] = true; chk2.Checked = true; lev = lev - 2; } else chk2.Checked = false;
            if (lev >= 1) { level[1] = true; chk1.Checked = true; lev = lev - 1; } else chk1.Checked = false;
            if (lev <= 0) bucle = false;
        }
        CNx2.Close();
    }

    protected void btnUP3_Click(object sender, EventArgs e)
    {
        int op = int.Parse(hid3.Value);
        GrabarUbica(op);
    }

    private void GrabarUbica(int op)
    {
        string msg = "";
        string qry = "";
        if (op == 1)
        {
            qry = "Insert into LEG_Ubicacion (Descripcion) values ('" + hid2.Value + "')";
        }
        else if (op == 2)
        {
            msg = "Select count(*) from LEG_Ubicacion where IDUb=" + hid1.Value;
            qry = "Delete from LEG_Ubicacion where IDUb=" + hid1.Value;

        }
        else
        {
            qry = "Update LEG_Ubicacion set Descripcion = '" + hid2.Value + "' where IDUb=" + hid1.Value;
        }

        CNx.Open();
        if (msg != "")
        {
            SqlCommand te = new SqlCommand(msg, CNx);
            int res = (int)te.ExecuteScalar();
            if (res > 0)
            {
                string datos = "No puede eliminar este registro porque esa siendo utilizado!!";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "mensaje('" + datos + "');", true);
                return;
            }
        }
        SqlCommand tb = new SqlCommand(qry, CNx);
        tb.ExecuteNonQuery();
        CNx.Close();
        cargarubi();
    }
}